package Utility;


import java.io.*;

import sun.net.*;
import sun.net.ftp.FtpClient;

public class FTP {
	private FtpClient sftpClient;
	private FtpClient cftpClient;
	private String localpath = "d:/TYZY";
	public int filenumber = 0;
	public int filenumber2 = 0;
	public long filesize = 0;
	MakeDir makedir = new MakeDir();
	/**
	 * connectServer
	 * 连接ftp服务器
	 * @throws java.io.IOException
	 * @param path 文件夹，空代表根目录
	 * @param password 密码
	 * @param user 登陆用户
	 * @param server 服务器地址
	 */
	public void connectServer(String server, String suser, String spassword,
			String path) throws IOException {
		// server：FTP服务器的IP地址；user:登录FTP服务器的用户名
		// password：登录FTP服务器的用户名的口令；path：FTP服务器上的路径
		sftpClient = new FtpClient();
		sftpClient.openServer(server);
		sftpClient.login(suser, spassword);
		//path是ftp服务下主目录的子目录
		File lpath = new File(localpath);
		if(!lpath.isDirectory())
		{
			makedir.makedirectory(localpath);
		}
		makedir.makedirectory(localpath+path);
		if (path.length() != 0)
			sftpClient.cd(path);
		//用2进制上传、下载
		sftpClient.binary();
	}
	public void connectServer(String server, String suser, String spassword,
			String cserver,String cuser,String cpassword,String spath,String cpath) throws IOException {
		// server：FTP服务器的IP地址；user:登录FTP服务器的用户名
		// password：登录FTP服务器的用户名的口令；path：FTP服务器上的路径
		sftpClient = new FtpClient();
		sftpClient.openServer(server);
		sftpClient.login(suser, spassword);
		cftpClient = new FtpClient();
		cftpClient.openServer(cserver);
		cftpClient.login(cuser, cpassword);
		
		
		if(!this.isDirExist(cpath))
		{
			this.createdir(cpath); 
		}
		
		//用2进制上传、下载
		if(cpath.length()!=0)
			sftpClient.cd(cpath);
		sftpClient.binary();
		if (cpath.length() != 0)
			cftpClient.cd(cpath);
		//用2进制上传、下载
		cftpClient.binary();
	}
	/**
	 * download
	 * 从ftp下载文件到本地
	 * @throws java.lang.Exception
	 * @return
	 * @param newfilename 本地生成的文件名
	 * @param filename 服务器上的文件名
	 */
	public long download(String filename, String newfilename) throws Exception {
		long result = 0;
		TelnetInputStream is = null;
		FileOutputStream os = null;
		try {
			is = sftpClient.get(filename);
			java.io.File outfile = new java.io.File(newfilename);
			os = new FileOutputStream(outfile);
			byte[] bytes = new byte[1024];
			int c;
			while ((c = is.read(bytes)) != -1) {
				os.write(bytes, 0, c);
				result = result + c;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}
		return result;
	}
	/*path ：传进来的源数据端路径
	 *Upload:真正的调用上传函数 
	 *UpLoad:一边遍历文件夹，如果是文件夹就在服务器端创建一个文件夹，如果是文件就直接调用Upload上传上去
	*/
	//private long filesize=0; //记录文件大小
	public boolean UpLoad(String path) 
	{
		try 
		{
			BufferedReader dis = null,cis = null;

			dis = new BufferedReader(new InputStreamReader(cftpClient.nameList(path)));
			String filename = "";
			String checkname = "";
            String fuckname = "";
		    while ((filename =dis.readLine()) != null) 
		    {
		    	checkname = filename;
		    	filename =path+"/"+filename;
				cis = new BufferedReader(new InputStreamReader(cftpClient.nameList(filename)));
				fuckname =cis.readLine();
				if(!checkname.equals(fuckname)) //获取的是一个文件夹
				{			
					if(!this.isDirExist(filename))
						this.createdir(filename);
					UpLoad(filename);
				}
				else
				{
					filesize+=this.Upload(filename);
				}
			}
		}catch (Exception e) 
		{
			e.printStackTrace();
			return false;
		}
		System.out.println("上传的文件总大小："+filesize+"字节");
		System.out.println("上传的文件总数据："+filenumber+"个");
		
	    return true;
	}
	
	public int CheckFileNumber(String path) 
	{
		try 
		{
			BufferedReader dis = null,cis = null;

			dis = new BufferedReader(new InputStreamReader(sftpClient.nameList(path)));
			String filename = "";
			String checkname = "";
            String fuckname = "";
		    while ((filename =dis.readLine()) != null) 
		    {
		    	checkname = filename;
		    	filename =path+"/"+filename;
				cis = new BufferedReader(new InputStreamReader(sftpClient.nameList(filename)));
				fuckname =cis.readLine();
				if(!checkname.equals(fuckname)) //获取的是一个文件夹
				{			

					CheckFileNumber(filename);
				}
				else
				{
					filenumber2++; //上传到FTP服务器的文件个数
				}
			}
		}catch (Exception e) 
		{
			e.printStackTrace();
		}
		System.out.println("FTP文件总数据："+filenumber2+"个");
		
	    return filenumber2;
	}
	

	/**
	 * closeServer
	 * 断开与ftp服务器的链接
	 * @throws java.io.IOException
	 */
	public void closeServer() throws IOException {
		try {
			if (sftpClient != null) 
			{
				sftpClient.closeServer();
				System.out.println("关闭连接成功");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void closeServer2() throws IOException {
		try {
			if (sftpClient != null&&cftpClient != null) 
			{
				sftpClient.closeServer();
				cftpClient.closeServer();
				System.out.println("关闭连接成功");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    public String getlocalpath()
    {
    	return localpath;
    }

	public FtpClient getFtpClient() {
		return sftpClient;
	}

	public void setFtpClient(FtpClient ftpClient) {
		this.sftpClient = ftpClient;
	}
	/**
	 * 上传文件
	 * @param filename 源主机文件名
	 * @param zhonfilename web服务器缓存上传的文件
	 * @param newname 目的主机文件名
	 * @return  传输的字节大小
	 * @throws Exception
	 */
	private String ftpDir = ""; 
	public long Upload(String filename) throws Exception {
		long result = 0;
		TelnetInputStream is = null;
		FileOutputStream os = null;
		FileInputStream Is = null;
		TelnetOutputStream Os = null;
		try {
			is = cftpClient.get(filename);

			Os = sftpClient.put(filename);

			byte[] bytes = new byte[1024];
			int c;
			
			while ((c = is.read(bytes)) != -1) 
			{
				Os.write(bytes, 0, c);
				result = result + c;
			}
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();

		} finally {
			
			if (Is != null) {
				Is.close();
			}
			if (Os != null) {
				Os.close();
			}
		}
		//this.deletedir(filename);
		filenumber++;
		return result;
	}
	
	/*
	 * 
	 */
	private long size=0;
	public long Download(String path)throws Exception
	{
		try 
		{
			BufferedReader dis = null,cis=null;

			dis = new BufferedReader(new InputStreamReader(sftpClient.nameList(path)));
			String filename = "";
			String checkname = "";
            String fuckname = "";
		    while ((filename =dis.readLine()) != null) 
		    {
		    	System.out.println("wojian:"+filename);
		    	checkname = filename;
		    	filename =path+"/"+filename;
				cis = new BufferedReader(new InputStreamReader(sftpClient.nameList(filename)));
				fuckname =cis.readLine();
				System.out.println("到底是什么："+fuckname);
				System.out.println("filename:"+filename);
				if(!checkname.equals(fuckname)) //获取的是一个文件夹
				{			
					makedir.makedirectory(localpath+filename);
					Download(filename);
				}
				else
				    size+=this.download(filename, localpath+filename);
			}
		}catch (Exception e) 
		{
			e.printStackTrace();
		}
		System.out.println("下载的文件总大小："+size+"字节");
	    return size;

	}
	
	public boolean Deletefile(String path)
	{
		try 
		{
			BufferedReader dis = null,cis = null;

			dis = new BufferedReader(new InputStreamReader(sftpClient.nameList(path)));
			String filename = "";
			String checkname = "";
            String fuckname = "";
		    while ((filename =dis.readLine()) != null) 
		    {
		    	checkname = filename;
		    	filename =path+"/"+filename;
				cis = new BufferedReader(new InputStreamReader(sftpClient.nameList(filename)));
				fuckname =cis.readLine();
				if(!checkname.equals(fuckname)) //获取的是一个文件夹
				{
					Deletefile(filename);
					
				}
				else
				    this.deletefile(filename);
			}
		}catch (Exception e) 
		{
			e.printStackTrace();
			return false;
		}
		return true;

	}
	
	public boolean Deletedir(String path)
	{
		try 
		{
			BufferedReader dis = null,cis = null;
			dis = new BufferedReader(new InputStreamReader(sftpClient.nameList(path)));
			String filename = "";
			String checkname = "";
            String fuckname = "";
		    while ((filename =dis.readLine()) != null) 
		    {
		    	checkname = filename;
		    	filename =path+"/"+filename;
				cis = new BufferedReader(new InputStreamReader(sftpClient.nameList(filename)));
				fuckname =cis.readLine();
				if(!checkname.equals(fuckname)&&fuckname!=null) //获取的是一个文件夹
				{					
					Deletedir(filename); //进入这个文件夹继续递归		
				}
				else
					this.deletedir(filename); //删除文件夹						   
			}
		    //this.deletedir(path); //删除文件夹
		}catch (Exception e) 
		{
			e.printStackTrace();
			System.out.println("删除目录失败！");
			return false;
		}
		return true;
	}
	
	public void deletefile(String filename) //远程删除文件
	{
		String cmd = "DELE " + filename+"\r\n";
		if(!this.isDirExist(filename)) //有这个文件夹
		{
			sftpClient.sendServer(cmd);
			System.out.println("成功删除文件："+filename);
		}
		else
			System.out.println("文件不存在："+filename);

	}
	public void deletedir(String filename) //远程删除文件夹
	{
		String cmd = "RMD " + filename+"\r\n";
		if(this.isDirExist(filename)) //有这个文件夹
		{
			sftpClient.sendServer(cmd);
		}
		else
			System.out.println("文件夹不存在："+filename);

	}
	public void createdir(String filename)
	{		
		String cmd = "MKD "+filename+"\r\n";
		sftpClient.sendServer(cmd);
		System.out.println("创建远程目录成功："+cmd);
	}
	
	public boolean isDirExist(String dir) 
	{
		try 
		{
			sftpClient.cd(dir);
		}catch (Exception e) 
		{
		   return false;
		}
		System.out.println("文件夹存在");
		return true; //表示有这个文件夹
	}
	
	public static void main(String[] args) throws Exception{
           FTP ftp = new FTP();
           ftp.connectServer("192.168.1.100", "tyzy", "tyzy", "");
           ftp.Download("软件的黄金时代.txt");
           ftp.closeServer();
	}
	
}
